Cookies and Sessions
Learn about web cookies and sessions and how they are related.
Introduction#
A typical HTTP request-response cycle is stateless because servers consider each incoming request to be a brand new one. The primary reason for this kind of behavior is to enable the server-side to service many incoming requests and increase scalability as a result. Many use cases need the server-side to remember what the client has done before—meaning some state is required for each client. For example, if a customer wants to reserve an airplane ticket, they have to go through several steps involved in this process. This process requires many pages to be accessed, and the user’s state (information) must be kept across all the pages. Cookies and sessions are the two ways to maintain the user’s state and improve the user’s experience. Let's discuss them in detail in the following sections.
Cookies#
A cookie is a small amount of data stored by a specific website (server) on the user's computer. The data stored in the cookies is labeled with a unique ID. It’s exchanged between a client's browser and the server, where the server reads the cookies and decides what information needs to be provided to the user.
Cookies contain information about the user's activity on the website. This includes the user's IP address, web browser type, version, operating system, and the pages the user has visited. Some other relevant information stored in a cookie includes clicks on different items or objects and the actions performed by the client—for example, views, time spent, items added to a cart, and so on.
When a user sends a request to a web server to visit a website, a response from the server contains the Set-Cookie header representing details about the cookies, as shown below. The client sends this cookie in response to future requests to the web server.
Name: This is the name of the cookie.
Value: The information that is stored on the user’s computer by the website.
Expires: When the cookie will expire.
Domain: This indicates the server to which the cookie is sent in future requests.
Path: Represents an entity on the server that will receive the cookie.
How are cookies created?#
Let's understand cookie creation with an example. Let’s assume that Alice connects with the web using a newly installed browser and contacts the website www.example.com. When they visit the website for the first time, the server sends cookie data in response to Alice’s browser consisting of the unique ID. The cookies are stored locally and are sent in the requests to the same website, as shown in the figure below.
Note: A browser usually has an upper limit on the number of cookies that it can store per domain. For example, few browsers allow storing up to 50 cookies per domain, and the amount of information a server sends to the client is small (usually no more than 4 KB).
The following table shows different attributes of a cookie object while visiting www.google.com.
A Cookie After Visiting www.google.com
Attribute | Value | Attribute | Value |
Name | __Secure-3PSIDCC | HTTPOnly | ✓ |
Value | AEf-XMQjdJXL... | Secure | ✓ |
Domain | .google.com | SameSite | None |
Path | / | SameParty | _ |
Expires/Max-Age | 2023-09-07T08:09:56.552Z | Partition Key | _ |
Size | 91 | Priority | High |
Note: In the table above, the tick (✓) symbol means the values have been provided. Whereas "–" means the values have not been provided.
The cookies table in our browser contains the following fields:
- Name: The name of the cookie.
- Value: The information that’s stored on the user’s computer by the website. This information can include the user’s name, password, and preferences.
- Domain: This represents the domain that is allowed to receive the cookie.
- Path: This shows a specific path or URL on the website for which the cookie is valid.
- Expires/Max-Age: This is the expiration date or the maximum age of the cookie.
- Size: The cookie size in bytes.
- HTTPOnly: This indicates whether the cookie should only be used over HTTP or can be modified through JavaScript.
- Secure: It indicates that the cookie can be sent to the server over HTTPS, if true.
- SameSite: This field contains values
lax,strict, orNone. Thelaxvalue shows that the cookies can be sent on some cross-site requests, whereas thestrictvalue doesn’t allow cookies on cross-site requests. TheNonevalue shows that the cookies can be sent to both cross-site and same-site requests. - SameParty: This field indicates whether the party from which the user accessed the site is the same as the party that set the cookie.
- Partition Key: The partition key is used in the case when we have a site embedding content from another site. For example,
https://abc.comembeds content fromhttps://xyz.com. The partition key is used to provide support for cross-site cookies. This key represents the top-level URL we are accessing—for example,https://abc.com. The partition key in our case would be("https", "abc.com"). - Priority: The cookie priority field is used to indicate the priority of a given cookie. The field can take on one of three values:
Low,Medium, orHigh. The higher-priority cookies remain longer on the client than the low-priority cookies (the expiration date of these cookies are set by the server).
Note: Although cookies do not change the behavior of HTTP in any way, they do function as application-specific data storage that help maintain the state within an application according to different users.
What are cookies used for?#
Session management: Cookies can be used for session management. Upon exchanging cookies, the website recognizes users and their preferences. For example, whether a specific user likes to see news related to sports or politics.
Personalization: Cookies help the server-side maintain client-specific information. This helps in providing an experience that has been tailor-made for a particular user.
Tracking: Cookies are used to track users across websites. For example, when a user visits a website, a cookie is stored on their computer. The cookie contains information about the user, such as the pages they visited, the time they visited, and the time they spent on a specific page. This allows businesses to show targeted ads to users based on their interests. Cookies can also be used to track users' browsing history and activity. This information can be used to personalize the user's experience on a website or application.
There are several kinds of cookies that are classified by their purposes. For example, some cookies are used to store the sign-in details and website settings, while some are used to track users between websites to provide relevant ads and information. Some of the more well-known cookies are mentioned below:
- Session cookies: These cookies allow users to navigate multiple pages without having to enter their details again. These cookies keep the user’s activities as long as they are on a website. Common use cases are e-commerce websites where a user adds some item to the shopping cart before checkout.
- Persistent cookies: Persistent cookies are stored on the user’s computer even after the end of a session. They’re used for numerous purposes, such as remembering the username and password (in the form of hash) or the font size, language preferences, or data entered in a form. Persistent cookies usually last for longer periods of time than other types of cookies.
- First-party cookies: These cookies are generated by the website we visit. These cookies store information that the website needs to work correctly. For example, a first-party cookie might store our preferences for a website. These are similar to the ones we described earlier.
- Second-party cookies: These cookies are set by a website other than the one we’re visiting. It must be set with the permission of the website we’re currently visiting. Mainly, these cookies consist of data transferred from one company to another through a data partnership, such as a train service selling its first-party data to a trusted hotel chain for ad-targeting. They differ from their counterparts due to the fact that the data within them is shared from one source to a small audience.
- Third-party cookies: These cookies are generated by websites other than the ones we’re visiting. These cookies are used for a variety of purposes, such as tracking user behavior across different websites, targeting ads, and more. For example, Google Analytics and Facebook Pixel use a set of cookies to track user behavior across different websites, target ads, and so on.
- Zombie cookies: These cookies are a type of persistent cookie that is created when a user visits a web page that contains a script from a third-party domain. These cookies can be used to track the user’s behavior on the website and send targeted ads to the user. Most zombie cookies are created by third-party advertising companies that use web beacons to track users across different websites. These companies then use the information they collect to target ads to the user based on their web browsing history. Some browsers have extensions that can block or delete zombie cookies, but they are not always practical. The best way to avoid having your web browsing tracked by zombie cookies is to disable third-party cookies in your browser’s settings.
Note: Some cookies are the subtypes of other cookies—for example, zombie cookies are third-party cookies.
Points to Ponder
Question 3
What happens if a cookie is stolen?
If a cookie is stolen, it can be used to gain access to the user’s account. This is because the cookie contains information about the user, such as their preferences and authentication credentials. An attacker can use this information to access the user’s account and potentially steal sensitive data. It’s crucial to ensure that cookies are stored securely and are not accessible to attackers.
3 of 3
Note: Cookies can be deleted in your browser settings. You can find the settings in the “Options” or “Preferences” menu of your browser.
Sessions#
Sessions refer to the time users spend browsing a website. It represents the time between the user's arrival on a website's page and when they finish surfing it. A web session is a series of network activities that takes place between a web server and a web browser. During a session, the server and browser exchange a series of messages and information to establish a connection and start interacting with each other.
The interaction and the data exchanged between a web server and a web browser can include our search engine history, form data, added items to a shopping cart, ticket booking, the amount of time consumed on a page of a website, and so on. This data is exchanged via different kinds of cookies between the web server and the browser. To sum up, any interaction that we have with any website is recorded as a web session.
While sessions are often conflated and confused with cookies, they have some key differences from each other, as shown in the following table.
Sessions vs. Cookies
Sessions | Cookies |
|
|
|
|
|
|
|
|
Points to Ponder
Question 3
Are session IDs secure?
The data between the client and server are exchanged after establishing a secure connection. This secure connection helps to deliver the session ID securely to the user.
3 of 3
A single session between a web browser and the web server lasts for a certain duration. Depending on the use case, this session can be as short as a few minutes or as long as an entire day (or more).
Why is a web session used?#
Instead of storing a huge amount of data in the browser, developers use session IDs to save information on the server-side while preserving user privacy. Both sessions and cookies have unique IDs; therefore, a web application sends the session ID and cookie ID back to the server each time a user performs an action or submits a request, along with a description of the activity.
Note: Session IDs and cookie IDs are sometimes confused. They both are closely related but aren’t the same. Cookie IDs identify a specific computer or visitor and can be used for authentication, storing website preferences and server session identification. On the other hand, session IDs are used to identify a specific session. A client has only one cookie ID but may have several session IDs, these two can be used together to better track the preferences of the user and give them a better experience.
A session's role in APIs#
As discussed earlier, a session is a stateful connection between a client and a server. In the context of APIs, a session is typically used to store information about the state of a user's interaction with an API, such as authentication details, preferences, and progress. This information can then be used to customize the API experience for the user and provide a more seamless interaction.
Note: There’s plenty more stuff about cookies that we can talk about, but for the purpose of this course, this information will suffice. To conclude, cookies either benefit businesses or evade privacy. Therefore, some organizations support cookies while others oppose them. For example, Apple and Google clamped down on cookies (especially those that help track user activity), which hurt many advertisement businesses for big tech giants like Meta. On the other hand, Amazon supports and uses cookies for various purposes.
Summary#
To provide a better user experience in a number of applications, cookies play a vital role in exchanging crucial data between a client and a server. Cookies are also used to establish sessions on the server side. Web sessions are important because they allow website owners to track what users do on their websites. This information can be used to improve the user experience by making changes to the website based on how users interact with it. Additionally, web sessions can be used to track user behavior for marketing or advertising purposes.
Event-Driven Architecture Protocols
The Role of Idempotency in API Design